package com.hy.ratelimiting.controller;

import com.hy.ratelimiting.limiting.FixedWindowRateLimiter;
import com.hy.ratelimiting.limiting.LeakyBucketRateLimiter;
import com.hy.ratelimiting.limiting.SlidingWindowRateLimiter;
import com.hy.ratelimiting.limiting.TokenBucketRateLimiter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created With IntelliJ IDEA.
 * Descriptions：测试限流
 * <p>
 * User:Mr.Du
 * Date:2024/4/25
 * Time:10:57
 */
@Slf4j
@Controller
@RestController
@RequiredArgsConstructor
public class TestRateLimitingController {

    private final FixedWindowRateLimiter fixedWindowRateLimiter;

    private final SlidingWindowRateLimiter slidingWindowRateLimiter;

    private final LeakyBucketRateLimiter leakyBucketRateLimiter;

    private final TokenBucketRateLimiter tokenBucketRateLimiter;

    private AtomicInteger sC = new AtomicInteger(0);

    private AtomicInteger fC = new AtomicInteger(0);

    @GetMapping("/fixedWindow/testFixedWindowRateLimiter")
    public String testFixedWindowRateLimiter() {
        return getString(fixedWindowRateLimiter.allowRequest());
    }


    @GetMapping("/slideWindow/testSlidingWindowRateLimiter")
    public String testSlidingWindowRateLimiter() {
        return getString(slidingWindowRateLimiter.allowRequest());
    }

    @GetMapping("/leakyBucket/testLeakyBucketRateLimiter")
    public String testLeakyBucketRateLimiter() {
        return getString(leakyBucketRateLimiter.allowRequest());
    }

    @GetMapping("/tokenBucket/testTokenBucketRateLimiter")
    public String testTokenBucketRateLimiter() {
        return getString(tokenBucketRateLimiter.allowRequest());
    }

    private String getString(boolean b) {
        if(b){
            log.info("获取成功");
            log.info("成功count: {}", sC.incrementAndGet());
            return "获取成功";
        } else {
            log.info("获取失败");
            log.info("失败count: {}", fC.incrementAndGet());
            return "获取失败";
        }
    }
}
